package com.ptu.server.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ptu.dto.UserDTO;
import com.ptu.entity.Product;
import com.ptu.mapper.ProductMapper;
import com.ptu.server.ProductServer;
import com.ptu.util.PageResult;
import com.ptu.util.UserHolder;
import com.ptu.vo.HotVO;
import com.ptu.vo.ProductFlVO;
import com.ptu.vo.ProductVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class ProductServerImpl implements ProductServer {

    @Autowired
    ProductMapper productMapper;

    @Autowired
    RedisTemplate redisTemplate;


//    @Override
//    public List<ProductVO> getCategory(int categoryId) {
//        //1.生成key
//        String key = "product:category:" + categoryId;
//
//        //2.从redis中获取数据
//        List<ProductVO> categoryRedis = (List<ProductVO>) redisTemplate.opsForValue().get(key);
//
//        //3.判断数据是否为空
//        if (categoryRedis != null) {
//            //4.不为空返回
//            return categoryRedis;
//        }
//
//        //5.查询数据库
//        List<ProductVO> categoryMysql = productMapper.getCategory(categoryId);
//
//        if (categoryMysql.isEmpty()) {
//            //出现缓存击穿，缓存空数据
//            redisTemplate.opsForValue().set(key, Collections.emptyList(), 5, TimeUnit.MINUTES);
//        } else {
//            //6.缓存数据
//            redisTemplate.opsForValue().set(key, categoryMysql);
//        }
//
//        //7.返回
//        return categoryMysql;
//    }

    @Override
    public List<ProductFlVO> getCategory(int categoryId) {
        List<ProductFlVO> category = productMapper.getCategory(categoryId);
        return category;
    }

    @Override
    public ProductVO getDetailById(int id) {
        String key = "product:detail:" + id;

        // 1. 从缓存获取
        try {
            ProductVO cached = (ProductVO) redisTemplate.opsForValue().get(key);
            if (cached != null) {
                // 处理缓存空值（防止缓存穿透）
                if (cached.getId() == null) { // 假设空对象的id为null
                    System.out.println("缓存空值");
                    return null;
                }
                System.out.println("缓存命中");
                return cached;
            }
        } catch (Exception e) {
            // 反序列化失败时删除缓存
            System.out.println("反序列化失败");
            redisTemplate.delete(key);
        }

        // 2. 查询数据库
        ProductVO product = productMapper.getDetailById(id);

        // 3. 写入缓存
        if (product != null) {
            redisTemplate.opsForValue().set(
                    key,
                    product
            );
        } else {
            // 缓存空值防止缓存穿透（设置较短过期时间）
            redisTemplate.opsForValue().set(
                    key,
                    new ProductVO(), // 空对象
                    5,
                    TimeUnit.MINUTES
            );
        }

        return product;
    }




    @Override
    public List<ProductVO> getProductByName(String name, Integer categoryId) {
        List<ProductVO> list = productMapper.getProductByName(name, categoryId);
        return list;
    }

    @Override
    public void favorite(int id) {
        ProductVO detail = productMapper.getDetailById(id);
        int isFavorite = detail.getIsFavorite();
        if (isFavorite == 1) {
            isFavorite = 0;
        }else if (isFavorite == 0) {
            isFavorite = 1;
        }
        productMapper.collect(id, isFavorite);
    }

    //获取收藏列表
    @Override
    public List<ProductVO> getFavoriteList() {
//        //从UserHolder中获取用户id
//        UserDTO user = UserHolder.getUser();
//        int id = user.getId();
//        System.out.println("用户id: " + id);
//        List<ProductVO> favoriteList =productMapper.getFavoriteList(id);
//        System.out.println("收藏列表: " + favoriteList);
//        return favoriteList;
        return null;
    }

    @Override
    public PageResult getProuctList(String name, Integer categoryId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);

        Page<Product> page = productMapper.pageQuery(name, categoryId);
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    public Product adminGetDetailById(Long id) {
        System.out.println("adminGetDetailById");
        return productMapper.selectById(id);
    }

    @Override
    public void adminUpdate(Product product) {
        System.out.println("adminUpdate");
        
        productMapper.adminUpdateById(product);
        
        // 删除Redis缓存
        String key = "product:detail:" + product.getId();
        System.out.println("删除商品缓存");
        redisTemplate.delete(key);
    }

    @Override
    public void adminAdd(Product product) {
        System.out.println("adminAdd");
        productMapper.insert(product);
    }

    @Override
    public void delete(Long id) {
        System.out.println("delete");
        productMapper.deleteById(id);
        
        // 删除Redis缓存
        String key = "product:detail:" + id;
        System.out.println("删除商品缓存");
        redisTemplate.delete(key);
    }

    @Override
    public void start(Long id) {
        System.out.println("start");
        Product product = productMapper.adminSelectById(id);
        if (product.getStatus() == 1) {
            productMapper.startOrStop(id, 0);
        }else if (product.getStatus() == 0) {
            productMapper.startOrStop(id, 1);
        }
        
        // 删除Redis缓存
        String key = "product:detail:" + id;
        System.out.println("删除商品缓存");
        redisTemplate.delete(key);
    }

    @Override
    public List<HotVO> getHotListByCategory(String type, Integer categoryId) {
        List<HotVO> list = productMapper.getHotListByCategory(type, categoryId);
        return list;
    }

    @Override
    public List<HotVO> getUserHotListByCategory(String type, Integer categoryId) {
         //从UserHolder中获取当前用户ID
         UserDTO user = UserHolder.getUser();
         int userId = user.getId();

        List<HotVO> list = productMapper.getUserHotListByCategory(type, categoryId, userId);
        System.out.println("从数据库查询并封装后的用户销售榜单数据：" + list);
        return list;
    }
}
